package com.starblink.mine.personhome.ui.like.ui

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.apollographql.apollo3.api.Optional
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.rocketreserver.FetchLikedPostsByAccountIdQuery
import kotlinx.coroutines.launch

class LikeVM : BaseViewModel() {
    var accountId: String = ""
    var ccurrencyPageNo = 0 // 当前页数，默认是0
    private val listResponse: ListResponse = ListResponse()
    var listResponseLiveData: MutableLiveData<ListResponse> =
        MutableLiveData()

    /**
     * 保存服务器返回数据
     */
    inner class ListResponse {
        val totalList = ArrayList<FetchLikedPostsByAccountIdQuery.FetchLikedPostsByAccountId>() // 保存全部列表数据
        lateinit var pageList: List<FetchLikedPostsByAccountIdQuery.FetchLikedPostsByAccountId> // 保存单页请求数据
        var refresh: Boolean = true // true-下拉刷新，false表示加载更多
    }

    /**
     * 获取用户喜欢的发布列表
     * @param refresh: true表示请求首页，false表示请求下一页
     */
    fun getLikedPosts(refresh: Boolean = true) {
        val requestPageNo = if (refresh) 1 else ccurrencyPageNo + 1

        viewModelScope.launch {
            val response = SkGqlClient.skQuery(
                FetchLikedPostsByAccountIdQuery(
                    accountId = accountId,
                    pageNo = requestPageNo,
                    pageSize = Optional.present(PAGE_SIZE)
                ),
                showDefaultLoading = false
            )
            if (response?.data != null && response.data!!.fetchLikedPostsByAccountId != null) {
                ccurrencyPageNo = requestPageNo
                listResponse.apply {
                    pageList = response.data!!.fetchLikedPostsByAccountId!!
                    this.refresh = refresh

                    if(refresh){
                        totalList.clear()
                    }
                    totalList.addAll(pageList)
                }
                listResponseLiveData.postValue(listResponse)
            } else {
                // 加载失败，提示用户（已toast提示）
                loadError(null)
            }
        }
    }

    companion object {
        const val PAGE_SIZE = 20
    }
}